//
//  FristViewController.m
//  Second
//
//  Created by Alex on 16/7/13.
//  Copyright © 2016年 蓝鸥科技有限公司西安分公司. All rights reserved.
//

#import "FristViewController.h"

@interface FristViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,AVCaptureMetadataOutputObjectsDelegate>

@property (nonatomic, strong)UICollectionView *collertionView;
@property (nonatomic, strong)UIImageView *imageView;
@property (nonatomic, strong)UIImageView *head_image;
@property (nonatomic, strong)UILabel *name;
@property (nonatomic, strong)UILabel *place;
@property (nonatomic, strong)NSMutableArray *datasource;
@property (nonatomic, strong)AVCaptureSession *session;
@property (nonatomic, strong)AVCaptureVideoPreviewLayer *previewLayer;
@property (nonatomic, strong)UITextField *textField;
@end

@implementation FristViewController

- (UICollectionView *)collertionView {
    
    if (!_collertionView) {
        
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
        _collertionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, kHeight/3, kWidth, kHeight-234) collectionViewLayout:layout];
        _collertionView.dataSource = self;
        _collertionView.delegate = self;
        layout.itemSize = CGSizeMake(kWidth/2-15, kWidth/2+50);
        layout.sectionInset = UIEdgeInsetsMake(10, 10, 0, 10);
    }
    return _collertionView;
}

- (NSMutableArray *)datasource {
    
    if (!_datasource) {
        
        _datasource = [NSMutableArray array];
    }
    return _datasource;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemOrganize target:self action:@selector(rightAction)];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemOrganize target:self action:@selector(leftAction)];
    
    [self.collertionView registerNib:[UINib nibWithNibName:@"XMFristCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"frist_cell"];
    self.collertionView.showsHorizontalScrollIndicator = NO;
    self.collertionView.showsVerticalScrollIndicator = NO;
    
    self.collertionView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.collertionView];
    [_collertionView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.top.mas_equalTo(200);
        make.bottom.mas_equalTo(-44);
    }];
    
    NSArray *array = @[@"3.png",@"2.png"];
    ZHScrollView *scroll = [[ZHScrollView alloc]initWithFrame:CGRectMake(0, 0, kWidth, 200) imageArray:array];
    [self.view addSubview:scroll];
    
    
    [RequestManager fecthDataWithUrl:@"http://114.215.124.64/api/index.php/goods_list" parameter:@{} mehtod:@"POST" compelet:^(NSData *data) {
       
        NSDictionary *bigdic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"%@",bigdic);
        for (NSDictionary *dic in bigdic[@"data"]) {

            XMFristModel *model = [[XMFristModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [self.datasource addObject:model];
        }
        
    } updateUI:^{
    
        [self.collertionView reloadData];
    }];
    
    self.session = [[AVCaptureSession alloc]init];
  
 

}

- (void)rightAction {
    
    XMClassController *classVC = [[XMClassController alloc]init];
    
    [self.navigationController pushViewController:classVC animated:YES];
    
    
}

- (void)leftAction {
    
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    NSError *error = nil;
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
    if (error) {
        //防止模拟器崩溃
        NSLog(@"没有摄像头设备");
        return;
    }
    
    AVCaptureMetadataOutput *output=[[AVCaptureMetadataOutput alloc]init];
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    AVCaptureSession *session =[[AVCaptureSession alloc]init];
    [session setSessionPreset:AVCaptureSessionPresetHigh];
    [session addInput:input];
    [session addOutput:output];
    [output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]];
    self.session = session;
    AVCaptureVideoPreviewLayer *preview = [AVCaptureVideoPreviewLayer layerWithSession:_session];
    preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
    preview.frame = self.view.bounds;
    [self.view.layer insertSublayer:preview atIndex:100];
    self.previewLayer = preview;
    [_session startRunning];
}


#pragma mark -----------collectionViewDegelate-----------

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return self.datasource.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    XMFristCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"frist_cell" forIndexPath:indexPath];

    [cell setcellWithmodel:self.datasource[indexPath.row]];
    
    cell.backgroundColor = [UIColor colorWithRed:230/255.0 green:230/255.0 blue:230/255.0 alpha:1];
    cell.layer.masksToBounds = YES;
    cell.layer.cornerRadius = 10;
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    [[XMTabBer buttonWithTransform] buttonTransform];
    XMSecondController *second = [[XMSecondController alloc]init];
    second.shop_id = [self.datasource[indexPath.row] shop_id];
    second.model = self.datasource[indexPath.row];
    [self.navigationController pushViewController:second animated:YES];
    
}


//获得的数据在此方法中
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
    // 会频繁的扫描，调用代理方法
    // 1. 如果扫描完成，停止会话
    [self.session stopRunning];
    // 2. 删除预览图层
    [self.previewLayer removeFromSuperlayer];
    // 3. 设置界面显示扫描结果
    //判断是否有数据
    if (metadataObjects.count > 0) {
        AVMetadataMachineReadableCodeObject *obj = metadataObjects[0];
        //如果需要对url或者名片等信息进行扫描，可以在此进行扩展
    //    self.textField.text = obj.stringValue;
    }
    //结束扫描
    [self dismissViewControllerAnimated:YES completion:^{
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:self.textField.text preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
        [alert addAction:action];
        [self presentViewController:alert animated:YES completion:nil];
    }];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
    
}


@end
